<?php

namespace app\common\controller;

use think\Controller;
use app\common\traits\controller\TraitController;
use think\helper\Str;
use services\Payment as Payments;
use Endroid\QrCode\QrCode;
use think\Response;
use app\common\Token;
use think\Loader;
use think\Exception;
use think\Lang;

abstract class Payment extends Controller
{
    const RATIO   = '1:1';//旅行币与人民币比率

    private function getPaymentInfo($configs = [])
    {
    	return Payments::init($this->request->get('pt', 'WxPay'), $configs);
    }
	public function getDoPay()
	{
        Token::checkToken($this->request->param());

        $order_id   = $this->request->get('order_id');

        $order_info   = Loader::model('Orders')->getOrderInfo(['number' => $order_id]);
        $order_stage  = $order_info->getData('stage');
        $order_status = $order_info->getData('status');

        $r = new \ReflectionClass(Loader::model('Orders'));
        $constant = $r->getConstants();

        if ($order_stage == $constant['ORDER_PAYMENT_STAGE'] && $order_status == $constant['STATE_END']) {
            throw new Exception(Lang::get("Order has been paid successfully"), 30006);
        }

        if ($order_stage == $constant['ORDER_PAYMENT_STAGE']) {
            $difference = Loader::model('PaymentTransaction')->where(['number' => $order_info->number, 'status' => 0, 'type' => 'cash'])->value('price');

            if ($difference) {
                $difference = $difference * 100;
                
                if ($difference != $this->request->get('total/d')) {
                    throw new Exception("Abnormal order amount", 1);
                }

                $attributes = [
                    'body'         => $this->request->get('body'),
                    'detail'       => $this->request->get('detail'),
                    'out_trade_no' => $order_id,
                    'total_fee'    => $difference
                ];

                $result = $this->getPaymentInfo()->doPay($attributes);
                if ($result['code'] === 200) {

                    $rent_contact_id = $order_info->rent_contact_id;
                    if (!empty($rent_contact_id)) {
                        $contacts = Loader::model('user/ContactInfos')->where(['id' => ['IN', $rent_contact_id]])->select();
                        $this->assign('contacts', $contacts);
                    }
                    $this->assign('post_order_info', $order_info);

                    $data = [
                        'data'  => urlencode($result['data']),
                        'money' => $attributes['total_fee']/100,
                        'ratio' => self::RATIO
                    ];
                    return view('user@payment/weixincode', $data);
                }
            }
        }
        throw new Exception(Lang::get("Order status exception"), 30016);
	}
    /**
     * [getCheckPay 订单微信是否支付成功]
     * @param string $value [description]
     */
    public function getCheckPaySus()
    {
        $order_number = input('number');
        $res = db('orders')->where('number',$order_number)->value('paid_at');
        if (empty($res)) {
            return json(0);
        }else{
            return 1;
        }
    }
    /**
     * [sendWhichUser 发送邮件]
     * @param  [type] $type         [description]
     * @param  [type] $order_number [description]
     * @return [type]               [description]
     */
    public function sendWhichUser($order_number)
    {
        $theme = '双辉旅程网';
        $o_t = ['1'=>'出租','2'=>'交换'];
        $orderinfo  = model("Orders")->where('number',$order_number)->find();
        $type       = $orderinfo->source;
        $xia_dan    = $orderinfo->created_at;//halt($xia_dan);
        $start_date = $orderinfo->take_car_date;
        $end_date   = $orderinfo->leave_car_date;
        //车主邮箱
        $car_email = db('users')->where('id',$orderinfo->caravan_user_id)->value('email');
        $content1  = <<<data
尊敬的会员，您的房车于 $xia_dan 被他人下单。$o_t[$type]日期是 $start_date 至 $end_date 。
data;
        $this->sendEmail($car_email,$theme,$content1);
        //下单人邮箱
        $user_email = db('users')->where('id',$orderinfo->rent_user_id)->value('email');
        $content2  = <<<data
尊敬的会员，您于 $xia_dan 下单并支付成功。$o_t[$type]日期是 $start_date 至 $end_date ,祝您旅途愉快。
data;
        $this->sendEmail($user_email,$theme,$content2);
    }
     /**
     * [getCheckPay 充值旅行币微信是否支付成功]
     * @param string $value [description]
     */
    public function getCheckInterPaySus()
    {
        $order_number = input('number');
        $res = db('intergrateadd')->where('order_num',$order_number)->value('paid_at');
        if (empty($res)) {
            return json(0);
        }else{
            return 1;
        }
    }
    /**
     * [getShowInterface 订单微信支付页面]
     * @param  [type] $order_number [description]
     * @return [type]               [description]
     */
    public function getShowInterface($post_order_info)
    {
        $rent_contact_id = $post_order_info->rent_contact_id;
        if (!empty($rent_contact_id)) {
            foreach ($rent_contact_id as $k => $v) {
                $list = db('contactioninfo')->where('id',$v)->find();
                $contacts[] = $list;
            }
            $this->assign('contacts',$contacts);
        }
        $this->assign('post_order_info',$post_order_info);
    }
    /**
     * 自定义退款
     * @return [type] [description]
     */
    public function refund($out_trade_no, $total_fee, $refund_fee)
    {
        return $this->getPaymentInfo()->refund($out_trade_no, $total_fee, $refund_fee);
    }
    /**
     * 退除押金
     * @return [type] [description]
     */
    public function postRefundDeposit()
    {
        return $this->getPaymentInfo()->doRefundDeposit(input('post.out_trade_no')); 
    }
    /**
     * 退除订单款
     * @return [type] [description]
     */
    public function postRefundAll()
    {
        return $this->getPaymentInfo()->doRefundAll(input('post.out_trade_no')); 
    }
    /**
     * 订单查询
     * @return [type] [description]
     */
    public function getS($out_trade_no)
    {
    	//$out_trade_no = input('order_id');
    	return $this->getPaymentInfo()->doQ($out_trade_no);
    }
    /**
     * 通知信息
     * @return [type] [description]
     */
    public function postNotify()
    {
        return $this->getPaymentInfo()->doNotify();
    }
    /**
     * 获取支付模版
     * @param  string $type       [description]
     * @param  string $order_type [description]
     * @return [type]             [description]
     */
    private function getPayTemplate($type = 'wx_pay', $order_type = 'order')
    {
        switch ($order_type) {
            case 'order':
                $template = '_code';
                break;
            case 'recharge':
                $template = '_integral';
                break;
            default:
                $template = '_code';
                break;
        }
        return $type.$template;        
    }

    public function getQrcodes()
    {
        $data = input('get.data');
        $size = input('get.size',300);
        $logo_size = $size / 2;

        $qrCode = new QrCode();
        $qrCode->setText($data)
               ->setSize($size)
               ->setPadding(10)
               ->setErrorCorrection('high')
               ->setLogo(self::LOGOURL)
               ->setLogoSize($logo_size)
               ->setImageType(QrCode::IMAGE_TYPE_PNG);

        return new Response($qrCode->get(), 200, array('Content-Type' => $qrCode->getContentType()));
    }
}
